﻿#region Using Region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using CALTypeLib;
/*
using Unisys.InfoImage.IIFCAL;
using Unisys.InfoImage.IIFCAL.IIFClient;
using Unisys.InfoImage.IIFCAL.IIFClient.IIFWorkitem;
using Unisys.InfoImage.IIFCAL.IIFClient.IIFWorkitem.IIFWorkitemInformation;
using Unisys.InfoImage.IIFCAL.IIFClient.IIFQueue;
 * */
using ICE.Vacations.Datos.FileManager;


#endregion
namespace ICE.Vacations.IIF
{
    public  class IIFConnection
    {

        #region Global Resources

        protected internal  CALMaster CALMaster = new CALMaster();
        protected internal CALClient calClient;
        protected internal CALClientList calClientList;
        protected internal  CALQueues calQueues;
        protected internal  CALClientListItem calClientListItem;
        protected internal  CALClientListItems calClientListItems;
       // protected internal CALWorkitemInfo CALWorkitemInfo;

        private  bool abortProcessing;

        private  int TIMEOUT_MILISECS = 25000;
        private  int TIMEOUT_MILISECS_PROCESS = 60000;

        #endregion

        
       

        /// <summary>
        /// 
        /// </summary>
        /// <param name="username">InfoImage User</param>
        /// <param name="password">InfoImage user password</param>
        /// <param name="domain">InfoImage Domain</param>
        /// <returns>Returns True if the connection was seccessfull</returns>
        protected  bool CreateIIFClient(string username, string password, string domain)
        {
            const long OMDCLIENTCREATE_APPLYFUNCSEC = 0x0001;
            const int CALQueueListWorkstep = 128;

            try
            {
                Logger.fileWrite("Intentando conectarse al servidor de InfoImage [" + domain + "]...", Logger.MessageType.Information);

                if (calClient == null)
                {
                  
                    CALMaster = new CALMaster();
                   //IIFCALMaster.Destroy();
                    calClient = (CALClient)CALMaster.CreateClient(username, password, domain, OMDCLIENTCREATE_APPLYFUNCSEC);
                    calClientList = (CALClientList)calClient.ClientList;
                    calQueues = (CALQueues)calClient.get_Queues(CALQueueListWorkstep);
                }
                else
                {
                    Logger.fileWrite("Intentando conectar con usuario [" + username + "]", Logger.MessageType.Information);
                    //IIFCALMaster.Destroy();
                    calClient = (CALClient)CALMaster.CreateClient(username, password, domain, OMDCLIENTCREATE_APPLYFUNCSEC);
                    calClientList = (CALClientList)calClient.ClientList;
                    calQueues = (CALQueues)calClient.get_Queues(CALQueueListWorkstep);

                }
                Logger.fileWrite("Conexión a IIFestablecida correctamente", Logger.MessageType.Information);
                return true;
            }
            catch (Exception calException)
            {
                Logger.fileWrite("Se produjo un problema de conexion Error: " + calException.Message , Logger.MessageType.Error);
                int cont = 0;
                while (cont != 2)
                {
                    System.Threading.Thread.Sleep(10*1000);
                    try
                    {
                        CALMaster = new CALMaster();
                        
                        //IIFCALMaster.Destroy();
                        calClient = (CALClient)CALMaster.CreateClient(username, password, domain, OMDCLIENTCREATE_APPLYFUNCSEC);
                        calClientList = (CALClientList)calClient.ClientList;
                        cont = 2;
                    }
                    catch
                    {
                        cont++;
                    }
                }
                throw (calException);
            }

        }

        protected  void DestroyIIFClient()
        {
            try
            {
                if (calClient != null)
                {
                    if (!abortProcessing)
                    {
                        DestroyIIFClientExplicit();

                        //CALMaster.Destroy();
                    }
                }
            }
            catch (Exception calException)
            {
                Logger.fileWrite("ERROR [DestroyIIFClient] CAL Error: " + calException.Message, Logger.MessageType.Error);
            }
        }

        protected  void DestroyIIFClientExplicit()
        {
            try
            {
                if (calClient == null)
                {
                    Logger.fileWrite("No se encuentran sesiones abiertas para el usuario", Logger.MessageType.Information);
                }
                else
                {
                    Logger.fileWrite("Detectamos una sesión abierta para el usuario procediendo a cerrarla..", Logger.MessageType.Information);
                    abortProcessing = true;

                    var subThread = new Thread(delegate()
                    {
                        try
                        {
                            calClient.Destroy(DestroyConstants.calDestroySaveChanges);
                            //CALMaster.Destroy();
                        }
                        catch (Exception calException)
                        {
                            Logger.fileWrite("ERROR [DestroyIIFClientExplicit::calDestroySaveChanges - Inner Thread] CAL Error " + calException.Message + ".", Logger.MessageType.Error);
                        }

                    });

                    subThread.Start();
                    var threadResult = subThread.Join(TIMEOUT_MILISECS);

                    if (threadResult == true)
                    {
                        Logger.fileWrite("Sesión cerrada exitosamente.", Logger.MessageType.Information);
                        return;
                    }
                    else
                    {
                        Logger.fileWrite("Una excepción de timeout ha ocurrido, tratando de cerrar la sesión, proceso abortado. Tratando un nuevo intento descartando cambios.", Logger.MessageType.Error);
                    }

                    if (!threadResult)
                    {
                        subThread = new Thread(delegate()
                        {
                            try
                            {

                                calClient.Destroy(DestroyConstants.calDestroyAbortChanges);
                            }
                            catch (Exception calException)
                            {
                                Logger.fileWrite("ERROR [DestroyIIFClientExplicit::calDestroyAbortChanges - Inner Thread] CAL Error : " + calException.Message, Logger.MessageType.Error);
                                throw (calException);
                             
                            }
                        });
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.fileWrite("ERROR [DestroyIIFClientExplicit:] CAL Error : " + exception.Message, Logger.MessageType.Error);

            }
        }

        protected   void ClearIIFClientDesktop()
        {
            try
            {
                if (calClient != null)
                {
                    var subThread = new Thread(delegate()
                    {
                        try
                        {
                            if (!abortProcessing)
                            {
                                calClientList.Clear(ClientListClearConstants.calClearSendModWIP);
                            }

                        }
                        catch (Exception calException)
                        {
                            if (!abortProcessing)
                            {
                                //Se produjo un error
                            }
                        }
                    });

                    subThread.Start();
                    var threadResult = subThread.Join(TIMEOUT_MILISECS);

                    if (threadResult == true)
                    {
                        // Escritorio normalizado
                    }
                    else
                    {
                        //Ha ocurrido una excecpcion de timeout urante la normalizacion del escritorio. Proceso abortado.
                    }
                }
            }
            catch (Exception calException)
            {
                //ERROR [ClearIIFClientDesktop] CAL Error 
            }
        }

        protected  void CheckStatusIIFClientDesktop()
        {
            try
            {

                calClientListItems = (CALClientListItems)calClientList.AllItems;


                foreach (CALClientListItem listItem in calClientListItems)
                {
                    CALWorkitemInfo wii = (CALWorkitemInfo)listItem.Info;
                    if (wii.Status == ObjStatusConstants.calObjStatusWIP)
                    {
                        listItem.SendToDefault(SendConstants.calSendDiscard);
                    }
                }
            }
            catch (Exception exc)
            {
                // exc.APIErrorCode 



            }
        }

    }
}
